package org.example;

/**
 * Copyright (c) 2023-2033 All Rights Reserved
 * 线程方法 与 状态转换：sleep()
 *
 * 1 创建线程，线程进入 NEW 状态
 * 2 运行线程，线程进入 RUNNABLE 状态
 * 3 子线程 sleep()
 * 4 主线程 sleep() 修改flag，继续 sleep()
 * 5 子线程还在 sleep() 进入 TIMED_WAITING 状态
 * 6 如果子线程睡眠时间比主线程短，会进入 TERMINATED 状态
 *
 * 打印结果：
 * thread state = NEW
 * thread state = RUNNABLE
 * thread running flag is true
 * thread sleep state = TIMED_WAITING
 * thread running flag is false
 *
 * @date: 2023/5/5
 */
public class ThreadStatus {
    static volatile boolean flag = true;

    public static void main(String[] args) throws Exception{
        threadSleep();
        interrupted();
    }

    public static void threadSleep() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                while (flag) {
                    System.out.println("thread running flag is true");
                    Thread.sleep(10000L);
                }
                System.out.println("thread running flag is false");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 1 NEW
        System.out.println("thread state = " + thread.getState());

        thread.start();

        // 2 RUNNABLE
        System.out.println("thread state = " + thread.getState());

        Thread.sleep(2000L);

        flag = false;

        Thread.sleep(2000L);

        // 4 TIMED_WAITING
        System.out.println("thread sleep state = " + thread.getState());
    }

    public static void interrupted() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("thread is RUNNING");
        });
        thread.start();

        System.out.println("thread.isInterrupted() = " + thread.isInterrupted());

        thread.interrupt();

        System.out.println("thread.isInterrupted() = " + thread.isInterrupted());

        Thread.interrupted();

        System.out.println("thread.isInterrupted() = " + thread.isInterrupted());

        Thread.interrupted();

        System.out.println("thread.isInterrupted() = " + thread.isInterrupted());


        thread.getState();
        thread.run();
        thread.join(); // throws InterruptedException
        thread.start();
        thread.wait();  // throws InterruptedException
        thread.notify();

        thread.interrupt();
        thread.isInterrupted();  // 传 false

        Thread.interrupted();  // 传 true
        Thread.sleep(1000L); // throws InterruptedException
        Thread.yield();
        Thread.currentThread();
    }
}



